package com.gimi.cloud.jimi.queue.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.gimi.cloud.jimi.common.enums.ResponseCodeEnum;
import com.gimi.cloud.jimi.common.exception.MsgException;
import com.gimi.cloud.jimi.common.utils.DateUtil;
import com.gimi.cloud.jimi.commonService.InterfacePlatform.InterfacePlatformRequestService;
import com.gimi.cloud.jimi.dao.dao.User.UserDao;
import com.gimi.cloud.jimi.dao.dao.moreInfo.MoreInfoDao;
import com.gimi.cloud.jimi.dao.dao.moreInfo.MoreInfoLogDao;
import com.gimi.cloud.jimi.dao.dao.sys.SysConfigDao;
import com.gimi.cloud.jimi.entity.app.moreInfo.MoreInfoEntity;
import com.gimi.cloud.jimi.entity.app.moreInfo.MoreInfoLogEntity;
import com.gimi.cloud.jimi.entity.user.User;
import com.gimi.cloud.jimi.dto.params.SocialSecurityParam;
import com.gimi.cloud.jimi.queue.service.FengchaoShebaoService;
import com.rabbitmq.client.Channel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;

/**
 * @auther loongs
 * @date 2018/1/12  9:14
 */
@Service
public class FengchaoShebaoServiceImpl implements FengchaoShebaoService {

    private static final Logger logger = LoggerFactory.getLogger(FengchaoShebaoServiceImpl.class);

    private InterfacePlatformRequestService ipRequestService;
    private MoreInfoDao moreInfoDao;
    private MoreInfoLogDao moreInfoLogDao;
    private UserDao userDao;
    private SysConfigDao sysConfigDao;

    //最大容错次数暂时定为3次
    private final Integer MAXTIMES = 3;
    private final static String INTERFACE_PLATFORM_UNIVERSAL_SOCIALSECURITY = "interface_platform_universal_socialSecurity";

    @Autowired
    public FengchaoShebaoServiceImpl(InterfacePlatformRequestService ipRequestService, MoreInfoDao moreInfoDao, UserDao userDao, SysConfigDao sysConfigDao
            , MoreInfoLogDao moreInfoLogDao) {
        this.ipRequestService = ipRequestService;
        this.moreInfoDao = moreInfoDao;
        this.userDao = userDao;
        this.sysConfigDao = sysConfigDao;
        this.moreInfoLogDao = moreInfoLogDao;
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public void reveiveSheBaoData(Message message, Channel channel, SocialSecurityParam socialSecurityParam) throws IOException {

        User user = userDao.getUserByUserId(socialSecurityParam.getOperUserId());
        if (user == null) {
            throw new MsgException(ResponseCodeEnum.ERR_USER_INVALID);
        }
        //查询该用户之前是否有获取过社保信息，需要获取状态为获取中
        MoreInfoEntity moreInfoEntity = moreInfoDao.getMoreInfoByUserIdAndTypeAndData(socialSecurityParam.getOperUserId(),7,1);
        if (moreInfoEntity != null && moreInfoEntity.getGetdataErrorTimes() >= MAXTIMES) {
            throw new MsgException(ResponseCodeEnum.SHEBAO_DATA_ERROR_TIMES_IS_OUT_OF_TIMES);
        }
        //新建日志记录
        MoreInfoLogEntity moreInfoLogEntity =new MoreInfoLogEntity();

        String socialSecurity = sysConfigDao.getConfigByKey(INTERFACE_PLATFORM_UNIVERSAL_SOCIALSECURITY);

        try {
            JSONObject socialSecurityJson = JSON.parseObject(socialSecurity);
            JSONObject getdetailsinfo = socialSecurityJson.getJSONObject("getdetailsinfo");
            JSONObject body = getdetailsinfo.getJSONObject("body");
            body.put("sessionToken", socialSecurityParam.getSessionToken());

            getdetailsinfo.put("body", body);
            logger.info("获取社保信息，请求参数：" + getdetailsinfo.toJSONString());
            String sendApiPost = ipRequestService.sendApiPost(getdetailsinfo.toJSONString());

            //存入日志
            moreInfoLogEntity.setAddTime(DateUtil.getNow());
            moreInfoLogEntity.setResponseData(sendApiPost);
            moreInfoLogEntity.setRequestData(getdetailsinfo.toJSONString());
            moreInfoLogEntity.setUserId(user.getUserId());
            moreInfoLogEntity.setType("7");

            JSONObject reportJson = JSON.parseObject(sendApiPost);
            JSONObject reportBody = reportJson.getJSONObject("body");
            JSONObject reportHead = reportJson.getJSONObject("head");
            if (reportBody == null || !"0".equals(reportHead.getString("status"))) {
                throw new MsgException(ResponseCodeEnum.SERVICE_ERROR, reportHead.getString("responseDescription"));
            }
            JSONObject data = reportBody.getJSONObject("data");
            String type = reportBody.getString("type");
            logger.info("获取社保信息，返回参数：" + sendApiPost);

            //只有type为1的时候为成功，其他情况都是失败
            if (reportJson != null && "1".equals(type)) {
                moreInfoEntity.setReportData(data.getString("ossUrl"));
                //TODO 有效时长，等风控规则
                moreInfoEntity.setReportEffectionBegin(DateUtil.getNow());
                moreInfoEntity.setReportEffectionEnd(DateUtil.getLateYear(1));
                moreInfoEntity.setGetdataTime(DateUtil.getNow());
                //2代表成功
                moreInfoEntity.setGetdata("2");
                moreInfoEntity.setUpdateUid(user.getUserId());
                moreInfoEntity.setUpdateUname(user.getAddUname());
                moreInfoEntity.setUpdateTime(DateUtil.getNow());
                moreInfoEntity.setGetdataErrorTimes(0);
                moreInfoEntity.setBaRemark("");

                //抓取状态（1成功，2失败）
                moreInfoLogEntity.setStatus(1);

            } else {
                moreInfoEntity.setGetdataErrorTimes(moreInfoEntity.getGetdataErrorTimes() + 1);
                moreInfoEntity.setGetdata("3");
                moreInfoEntity.setUpdateUid(user.getUserId());
                moreInfoEntity.setUpdateUname(user.getAddUname());
                moreInfoEntity.setUpdateTime(DateUtil.getNow());

                //抓取状态（1成功，2失败）
                moreInfoLogEntity.setStatus(2);
            }
            moreInfoLogDao.insertSelective(moreInfoLogEntity);
            moreInfoDao.updateByPrimaryKey(moreInfoEntity);
        } catch (MsgException e) {
            logger.debug(e.getMsgEnum().getDesc(), e);
            moreInfoEntity.setGetdataErrorTimes(moreInfoEntity.getGetdataErrorTimes() + 1);
            moreInfoEntity.setGetdata("3");
            moreInfoEntity.setUpdateUid(user.getUserId());
            moreInfoEntity.setUpdateUname(user.getAddUname());
            moreInfoEntity.setUpdateTime(DateUtil.getNow());
            moreInfoEntity.setBaRemark(e.getMsgEnum().getDesc());
            moreInfoDao.updateByPrimaryKey(moreInfoEntity);

            //抓取状态（1成功，2失败）
            moreInfoLogEntity.setStatus(2);
            moreInfoLogEntity.setRemark(e.getMsgEnum().getDesc());
            moreInfoLogDao.insertSelective(moreInfoLogEntity);
        } catch (Exception e) {
            logger.info("日志信息处理失败，已自动取消!");
            logger.error(e.getMessage(), e);
        } finally {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        }
    }
}
